package com.ziyia.listviewtest;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.text.Layout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import java.util.List;

public class FruitAdapter extends ArrayAdapter<Fruit> {
    private Context context;
    private Integer resourceId;
    private List<Fruit> fruits;


    public FruitAdapter(@NonNull Context context, int resource, List<Fruit> fruits) {
        super(context, resource);
        this.context = context;
        this.resourceId = resource;
        this.fruits = fruits;
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        View view;
        ViewHolder viewHolder;
        if (convertView == null) {
            view = LayoutInflater.from(context).inflate(resourceId, parent, false);
            TextView fruitName = view.findViewById(R.id.fruitName);
            ImageView fruitImage = view.findViewById(R.id.fruitImage);
            viewHolder = new ViewHolder(fruitName, fruitImage);
            view.setTag(viewHolder);
        } else {
            view = convertView;
            viewHolder = (ViewHolder) view.getTag();
        }

        Fruit fruit = getItem(position);
        if (fruit != null) {
            viewHolder.textView.setText(fruit.getName());
            viewHolder.imageView.setImageResource(fruit.getImageId());
        }
        return view;
    }

    @Nullable
    @Override
    public Fruit getItem(int position) {
        return fruits.get(position);
    }

    @Override
    public int getCount() {
        return fruits.size();
    }

    class ViewHolder {
        private TextView textView;
        private ImageView imageView;

        public ViewHolder() {
        }

        public ViewHolder(TextView textView, ImageView imageView) {
            this.textView = textView;
            this.imageView = imageView;
        }

        public TextView getTextView() {
            return textView;
        }

        public void setTextView(TextView textView) {
            this.textView = textView;
        }

        public ImageView getImageView() {
            return imageView;
        }

        public void setImageView(ImageView imageView) {
            this.imageView = imageView;
        }

        @Override
        public String toString() {
            return "ViewHolder{" +
                    "textView=" + textView +
                    ", imageView=" + imageView +
                    '}';
        }
    }
}
